import os
import random
import re
import shutil
import sys

import exifread
# from result.main import main
from A import Ui_Dialog as A_Ui
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QIntValidator
# import cv2
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QMainWindow, QFileDialog
from face_search import Ui_Dialog as face_Ui
from main import rename
from the_time import Ui_Dialog as time_Ui
from tsearch import Ui_Dialog as search_Ui
from upload import main as main

file_name = ""


# def to_search():
#     # 保存输入的值可以跳转到函数去执行搜索操作
#     content = tmain.lineEdit.text()
#     tmain.close()
#     TSearch.show()
#     TSearch.lineEdit.setText(content)
#     TSearch.func_search.click()

# def to_A():
#     tmain.close(), a.show()

# def to_PW():
#     tmain.close(), PWatch.show()

# def to_FS():
#     tmain.close()
#     FS.show()
#     FS.lineEdit_2.setText("0")
#     FS.lineEdit_3.setText("150")
#     FS.pushButton_3.click()

# def to_PW_BACK():
#     PWatch.close(), tmain.show()


# def Backa():
#     a.close(), tmain.show()


# def Backs():
#     TSearch.close(), tmain.show()

# def FSback():
#     FS.close(),tmain.show()
def to_A():
    a.show()


def Backa():
    a.close()


def find_date_image(pic_path):
    date = ''
    with open(pic_path, 'rb') as f:
        tags = exifread.process_file(f)
        for tag, value in tags.items():
            if re.match('.*Date.*', tag):
                date = str(value)
    f.close()
    return date


def let_open(s):
    if s == "人脸查找":
        FS.show()
        FS.lineEdit_2.setText("0")
        FS.lineEdit_3.setText("150")
        FS.pushButton_3.click()
    if s == "字段查找":
        TSearch.show()
        TSearch.func_search.click()
    if s == "日期查找":
        t_time.show()


def time_ok():
    set_t.close()
    t_time.year1.setText(set_t.get_year1)
    t_time.year2.setText(set_t.get_year2)
    t_time.month1.setText(set_t.get_month1)
    t_time.month2.setText(set_t.get_month2)
    t_time.day1.setText(set_t.get_day1)
    t_time.day2.setText(set_t.get_day2)
    t_time.timeSearch()


def face_ok():
    set_f.close()
    FS.ttmin.setText(set_f.get_tmin)
    FS.ttmax.setText(set_f.get_tmax)
    FS.FacenumSearch()


class IOControlBtn(QLabel):
    def __init__(self, parent=None, img_path="", width=280, hight=210):
        super(IOControlBtn, self).__init__(parent)
        # self.setStyleSheet(
        #     "QPushButton{\n"
        #     "border-image: url(\"%s\");\n"
        #     "}" % img_path)
        self.setFixedSize(width, hight)
        if img_path != "":
            jpg = QtGui.QPixmap(img_path).scaled(self.width(), self.height())
            self.setPixmap(jpg)
        else:
            pass


# class the_mainUi(QtWidgets.QMainWindow, the_main_Ui):
#     def __init__(self):
#         super(the_mainUi, self).__init__()
#         self.setupUi(self)
#         self.lineEdit.returnPressed.connect(to_search)


class AUi(QMainWindow, A_Ui):
    def __init__(self):
        super(AUi, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon("icon.png"))
        self.label = QLabel(self)
        self.label.setText("")
        self.label.setFixedSize(550, 400)

        self.label.setStyleSheet("QLabel{background:white;}"
                                 "QLabel{color:rgb(300,300,300,120);font-size:10px;font-weight:bold;font-family:宋体;}"
                                 )

    def openfile(self):

        fo = open("the_file.txt", "r+")
        self.the_path = fo.read()
        if not os.path.exists(self.the_path):
            self.the_path = "./picture"
            fo.write("./picture")
        fo.close()

        try:
            self.fname, _ = QFileDialog.getOpenFileName(self, 'open file', '/', "Image files (*.jpg *.gif *.png)")
            self.file_name = main(self.fname)

        except:
            pass
        self.textBrowser.setPlainText(self.fname)
        # fname 是图片路径
        jpg = QtGui.QPixmap(self.fname).scaled(self.label.width(), self.label.height())
        self.label.setPixmap(jpg)

        # # fname 是图片路径
        # jpg = QtGui.QPixmap(self.fname).scaled(self.label.width(), self.label.height())
        # self.label.setPixmap(jpg)

    def A_save(self):
        dirs = self.the_path + "/" + self.file_name[0]
        # mylist = os.listdir(dirs)
        shutil.copyfile(self.fname, dirs)  # 复制文件到文件夹
        if self.file_name[1] != None:
            dirs = './' + self.file_name[1] + '/' + self.file_name[0]
            shutil.copyfile(self.fname, dirs)  # 复制文件到文件夹

        self.msg()

    def msg(self):
        reply = QMessageBox.about(self, "提示", "保存成功")


class searchUi(QtWidgets.QMainWindow, search_Ui):
    def __init__(self):
        super(searchUi, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon("icon.png"))
        self.lineEdit_2.setValidator(QIntValidator(0, 65535))
        self.lineEdit_2.editingFinished.connect(self.t_range)
        self.lineEdit.returnPressed.connect(self.StringSearch)
        self.com.activated[str].connect(self.jump)
        self.the_path = ""
        self.row = 4
        self.total = 1
        self.page = 0
        self.get_path()

    def get_path(self):
        fo = open("the_file.txt", "r+")
        self.the_path = fo.read()
        if not os.path.exists(self.the_path):
            self.the_path = "./picture"
            fo.write("./picture")
        fo.close()

    def jump(self, s):
        if s != "字段查找":
            self.close()
            let_open(s)

    def openfile(self):

        fo = open("the_file.txt", "r")
        the_path = fo.read()
        if the_path == "":
            the_path = "./picture"
        fo.close()

        try:
            self.fname = QFileDialog.getExistingDirectory(self, '选择文件夹', the_path)
            # self.file_name = main(self.fname)

        except:
            pass

        fo = open("the_file.txt", "w")
        if self.fname != "":
            fo.write(self.fname)
        fo.close()
        # 函数衔接点1
        file_path = ""
        file_dict = {}
        file_dict = rename()
        for key, value in file_dict[0].items():
            os.rename(key, the_path + '/' + value)

        if self.fname != "" and self.fname != self.the_path:
            self.the_path = self.fname
            self.lineEdit.setText("")
            self.func_search.click()
        return file_dict

    def t_range(self):
        snum = self.lineEdit_2.text()
        if len(snum) == 0:
            self.lineEdit_2.setText("0")
            snum = "0"
        num = int(snum)
        if num > self.page:
            self.lineEdit_2.setText("%d" % self.page)
        if self.page > 0 and num == 0:
            self.lineEdit_2.setText("1")

    def StringSearch(self):
        file_dir = ""
        if os.path.exists(self.the_path):
            file_dir = self.the_path
        else:
            file_dir = "./picture"
        string = self.lineEdit.text()
        self.destfile = []
        for files in os.listdir(file_dir):
            file_string = os.path.splitext(files)[0].split(sep=' ')
            for item in file_string:
                if string in item:
                    self.destfile.append(files)
        self.total = len(self.destfile)
        self.page = (self.total + 11) // 12
        self.label_num = "共%d页" % self.page
        self.label.setText(self.label_num)
        if self.page != 0:
            self.lineEdit_2.setText("1")
        else:
            self.lineEdit_2.setText("0")
        self.get_picture()
        # if len(self.destfile) == 0 :
        #     self.lineEdit_2.setText("空")
        # else:
        #     self.lineEdit_2.setText(self.destfile[0])

    def jumpPage(self):
        snum = self.lineEdit_2.text()
        if snum == "":
            self.lineEdit_2.setText("1")
        self.get_picture()

    def add1(self):
        snum = self.lineEdit_2.text()
        num = int(snum)
        if num < self.page:
            num = num + 1
            snum = "%d" % num
            self.lineEdit_2.setText(snum)
            self.get_picture()

    def sub1(self):
        snum = self.lineEdit_2.text()
        num = int(snum)
        if num > 1:
            num = num - 1
            snum = "%d" % num
            self.lineEdit_2.setText(snum)
            self.get_picture()

    def get_picture(self):
        snum = self.lineEdit_2.text()
        num = int(snum)
        left = (num - 1) * 12
        self.addLabel(left)

    def removeLabel(self):
        while self.gridLayout_2.count():
            item = self.gridLayout_2.takeAt(0)
            widget = item.widget()
            widget.deleteLater()

    def addLabel(self, left):
        self.removeLabel()
        # print("total=%d" % self.total)
        if left >= 0:
            i = 0
            while (i < 12):
                if left < self.total:
                    t_path = self.the_path + "/" + self.destfile[left]
                else:
                    t_path = ""
                bot1 = IOControlBtn(self, t_path)
                self.gridLayout_2.addWidget(
                    bot1,
                    i // self.row,
                    i % self.row + 1, 1, 1)
                i = i + 1
                left = left + 1


class faceUi(QtWidgets.QMainWindow, face_Ui):
    def __init__(self):

        super(faceUi, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon("icon.png"))
        self.lineEdit_4.setValidator(QIntValidator(0, 65535))
        self.lineEdit_4.editingFinished.connect(self.t_range)
        self.com.activated[str].connect(self.jump)
        self.the_path = ""
        self.destfile = []
        self.row = 4
        self.total = 1
        self.page = 0
        self.get_path()

    def get_path(self):
        fo = open("the_file.txt", "r+")
        self.the_path = fo.read()
        if not os.path.exists(self.the_path):
            self.the_path = "./picture"
            fo.write("./picture")
        fo.close()

    def jump(self, s):
        if s != "人脸查找":
            self.close()
            let_open(s)

    def set_face_num(self):
        set_f.show()

    def openfile(self):

        fo = open("the_file.txt", "r")
        the_path = fo.read()
        if the_path == "":
            the_path = "./picture"
        fo.close()

        try:
            self.fname = QFileDialog.getExistingDirectory(self, '选择文件夹', the_path)
            # self.file_name = main(self.fname)

        except:
            pass

        fo = open("the_file.txt", "w")
        if self.fname != "":
            fo.write(self.fname)
        fo.close()

        # 函数衔接点2
        file_path = ""
        file_dict = {}
        file_dict, kind_dict = rename()
        for key, value in file_dict.items():
            os.rename(key, the_path + '/' + value)
        for key, value in kind_dict.items():
            if value is not None:
                a = "%d.jpg" % random.randint(1, 100000000)
                shutil.copyfile(key, value + a)

        if self.fname != "" and self.fname != self.the_path:
            self.the_path = self.fname
            self.ttmin.setText("0")
            self.ttmax.setText("150")
            self.pushButton_3.click()
        return file_dict

    def t_range(self):
        snum = self.lineEdit_4.text()
        if len(snum) == 0:
            self.lineEdit_4.setText("0")
            snum = "0"
        num = int(snum)
        if num > self.page:
            self.lineEdit_4.setText("%d" % self.page)
        if self.page > 0 and num == 0:
            self.lineEdit_4.setText("1")

    def get_num_2(self):
        smin = self.ttmin.text()
        smax = self.ttmax.text()
        if smax != "" and smin != "":
            tmax = int(smax)
            s = int(smin)
            if s > tmax:
                self.ttmax.setText(smin)

    def get_num_3(self):
        smin = self.ttmin.text()
        smax = self.ttmax.text()
        if smin != "" and smax != "":
            tmin = int(smin)
            s = int(smax)
            if s < tmin:
                self.ttmin.setText(smax)

    def FacenumSearch(self):
        file_dir = ""
        if os.path.exists(self.the_path):
            file_dir = self.the_path
        else:
            file_dir = "./picture"
        smin = self.ttmin.text()
        smax = self.ttmax.text()
        if smin != "" and smax != "":
            start = int(smin)
            end = int(smax)
            self.destfile = []
            for files in os.listdir(file_dir):
                k = os.path.splitext(files)[0]
                number = re.findall(r"\d+", k)
                if len(number) == 0:
                    continue
                number = int(number[0])
                if number >= start and number <= end:
                    self.destfile.append(files)
        self.total = len(self.destfile)
        self.page = (self.total + 11) // 12
        self.label_num = "共%d页" % self.page
        self.label.setText(self.label_num)
        if self.page != 0:
            self.lineEdit_4.setText("1")
        else:
            self.lineEdit_4.setText("0")
        self.get_picture()

    def jumpPage(self):
        snum = self.lineEdit_4.text()
        if snum == "":
            self.lineEdit_4.setText("1")
        self.get_picture()

    def add1(self):
        snum = self.lineEdit_4.text()
        num = int(snum)
        if num < self.page:
            num = num + 1
            snum = "%d" % num
            self.lineEdit_4.setText(snum)
            self.get_picture()

    def sub1(self):
        snum = self.lineEdit_4.text()
        num = int(snum)
        if num > 1:
            num = num - 1
            snum = "%d" % num
            self.lineEdit_4.setText(snum)
            self.get_picture()

    def get_picture(self):
        snum = self.lineEdit_4.text()
        num = int(snum)
        left = (num - 1) * 12
        self.addLabel(left)

    def removeLabel(self):
        while self.gridLayout_2.count():
            item = self.gridLayout_2.takeAt(0)
            widget = item.widget()
            widget.deleteLater()

    def addLabel(self, left):
        self.removeLabel()
        print("total=%d" % self.total)
        if left >= 0:
            i = 0
            while (i < 12):
                if left < self.total:
                    t_path = self.the_path + "/" + self.destfile[left]
                else:
                    t_path = ""
                bot1 = IOControlBtn(self, t_path)
                self.gridLayout_2.addWidget(
                    bot1,
                    i // self.row,
                    i % self.row + 1, 1, 1)
                i = i + 1
                left = left + 1


class timeUi(QtWidgets.QMainWindow, time_Ui):
    def __init__(self):
        super(timeUi, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon("icon.png"))
        self.lineEdit_2.setValidator(QIntValidator(0, 65535))
        self.lineEdit_2.editingFinished.connect(self.t_range)
        self.com.activated[str].connect(self.jump)

        self.the_path = ""
        self.row = 4
        self.total = 1
        self.page = 0
        self.get_path()
        self.setWindowIcon(QIcon("icon.png"))
        # self.adjust_day()

    def get_path(self):
        fo = open("the_file.txt", "r+")
        self.the_path = fo.read()
        if not os.path.exists(self.the_path):
            self.the_path = "./picture"
            fo.write("./picture")
        fo.close()

    def jump(self, s):
        if s != "日期查找":
            self.close()
            let_open(s)

    def set_time(self):
        set_t.show()

    def openfile(self):

        fo = open("the_file.txt", "r")
        the_path = fo.read()
        if the_path == "":
            the_path = "./picture"
        fo.close()

        try:
            self.fname = QFileDialog.getExistingDirectory(self, '选择文件夹', the_path)
            # self.file_name = main(self.fname)

        except:
            pass

        fo = open("the_file.txt", "w")
        if self.fname != "":
            fo.write(self.fname)
        fo.close()

        # 函数衔接点3
        file_path = ""
        file_dict = {}
        file_dict = rename()

        if self.fname != "" and self.fname != self.the_path:
            self.the_path = self.fname

        for key, value in file_dict[0].items():
            os.rename(key, the_path + '/' + value)
        return file_dict

    def t_range(self):
        snum = self.lineEdit_2.text()
        if len(snum) == 0:
            self.lineEdit_2.setText("0")
            snum = "0"
        num = int(snum)
        if num > self.page:
            self.lineEdit_2.setText("%d" % self.page)
        if self.page > 0 and num == 0:
            self.lineEdit_2.setText("1")

    def timeSearch(self):
        the_year1 = self.year1.text()
        the_month1 = self.month1.text()
        the_day1 = self.day1.text()
        the_year2 = self.year2.text()
        the_month2 = self.month2.text()
        the_day2 = self.day2.text()

        day30 = ["4", "6", "9", "11"]
        if the_year1 < "1980":
            the_year1 = "1980"
        if the_month1 < "01":
            the_month1 = "01"
        if the_day1 < "01":
            the_day1 = "01"
        the_year1 = the_year1.zfill(4)
        the_month1 = the_month1.zfill(2)
        the_day1 = the_day1.zfill(2)
        k_left = the_year1 + ":" + the_month1 + ":" + the_day1

        if the_year2 == "":
            the_year2 = "2050"
        if the_month2 == "":
            the_month2 = "12"
        if the_day2 == "":
            the_day2 = "31"
        the_year2 = the_year2.zfill(4)
        the_month2 = the_month2.zfill(2)
        the_day2 = the_day2.zfill(2)
        k_right = the_year2 + ":" + the_month2 + ":" + the_day2
        if k_left > k_right:
            reply = QMessageBox.about(self, "提示", "无效日期")
            return

        dir_list = os.listdir(self.the_path)
        if not dir_list:
            return
        else:
            dir_list = sorted(
                dir_list, key=lambda x: find_date_image(self.the_path + '/' + x))
        dir_dict = {}
        for item in dir_list:
            date = find_date_image(self.the_path + '/' + item).split(" ")[0]
            dir_dict[item] = date

        self.destfile = dir_list
        for item in dir_list:
            if dir_dict[item] < k_left:
                self.destfile.remove(item)
            if dir_dict[item] > k_right:
                self.destfile.remove(item)

        self.total = len(self.destfile)
        self.page = (self.total + 11) // 12
        self.label_num = "共%d页" % self.page
        self.label.setText(self.label_num)
        if self.page != 0:
            self.lineEdit_2.setText("1")
        else:
            self.lineEdit_2.setText("0")
        self.get_picture()
        return dir_list, dir_dict

    def jumpPage(self):
        snum = self.lineEdit_2.text()
        if snum == "":
            self.lineEdit_2.setText("1")
        self.get_picture()

    def add1(self):
        snum = self.lineEdit_2.text()
        num = int(snum)
        if num < self.page:
            num = num + 1
            snum = "%d" % num
            self.lineEdit_2.setText(snum)
            self.get_picture()

    def sub1(self):
        snum = self.lineEdit_2.text()
        num = int(snum)
        if num > 1:
            num = num - 1
            snum = "%d" % num
            self.lineEdit_2.setText(snum)
            self.get_picture()

    def get_picture(self):
        snum = self.lineEdit_2.text()
        num = int(snum)
        left = (num - 1) * 12
        self.addLabel(left)

    def removeLabel(self):
        while self.gridLayout_2.count():
            item = self.gridLayout_2.takeAt(0)
            widget = item.widget()
            widget.deleteLater()

    def addLabel(self, left):
        self.removeLabel()
        # print("total=%d" % self.total)
        if left >= 0:
            i = 0
            while (i < 12):
                if left < self.total:
                    t_path = self.the_path + "/" + self.destfile[left]
                else:
                    t_path = ""
                bot1 = IOControlBtn(self, t_path)
                self.gridLayout_2.addWidget(
                    bot1,
                    i // self.row,
                    i % self.row + 1, 1, 1)
                i = i + 1
                left = left + 1


class time_choose(QWidget):
    def __init__(self):
        super(time_choose, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("时间设置")
        self.setGeometry(600, 200, 400, 300)
        myframel1 = QFrame(self)
        myframel1.move(50, 50)
        fenge = QLabel(self)
        fenge.move(180, 90)
        myframel2 = QFrame(self)
        myframel2.move(50, 130)
        fenge.setText("至")
        self.nian1 = QLabel("年", myframel1)
        self.nian1.move(80, 3)
        self.tyear1 = QComboBox(myframel1)
        self.tyear1.setGeometry(0, 0, 70, 20)
        self.yue1 = QLabel("月", myframel1)
        self.yue1.move(180, 3)
        self.tmonth1 = QComboBox(myframel1)
        self.tmonth1.setGeometry(100, 0, 70, 20)
        self.ri1 = QLabel("日", myframel1)
        self.ri1.move(280, 3)
        self.tday1 = QComboBox(myframel1)
        self.tday1.setGeometry(200, 0, 70, 20)
        for item in range(22):
            str1 = "%d" % (2000 + item)
            self.tyear1.addItem(str1)
        for item in range(12):
            str2 = "%d" % (1 + item)
            self.tmonth1.addItem(str2)
        for item in range(31):
            str3 = "%d" % (1 + item)
            self.tday1.addItem(str3)

        self.nian2 = QLabel("年", myframel2)
        self.nian2.move(80, 3)
        self.tyear2 = QComboBox(myframel2)
        self.tyear2.setGeometry(0, 0, 70, 20)
        self.yue2 = QLabel("月", myframel2)
        self.yue2.move(180, 3)
        self.tmonth2 = QComboBox(myframel2)
        self.tmonth2.setGeometry(100, 0, 70, 20)
        self.ri2 = QLabel("日", myframel2)
        self.ri2.move(280, 3)
        self.tday2 = QComboBox(myframel2)
        self.tday2.setGeometry(200, 0, 70, 20)
        for item in range(22):
            str1 = "%d" % (2000 + item)
            self.tyear2.addItem(str1)
        for item in range(12):
            str2 = "%d" % (1 + item)
            self.tmonth2.addItem(str2)
        for item in range(31):
            str3 = "%d" % (1 + item)
            self.tday2.addItem(str3)

        butt = QPushButton(self)
        butt.setGeometry(170, 220, 50, 25)
        butt.setText("确认")
        butt.clicked.connect(self.to_get_time)

    def to_get_time(self):
        self.get_year1 = self.tyear1.currentText()
        self.get_year2 = self.tyear2.currentText()
        self.get_month1 = self.tmonth1.currentText()
        self.get_month2 = self.tmonth2.currentText()
        self.get_day1 = self.tday1.currentText()
        self.get_day2 = self.tday2.currentText()
        time_ok()


class face_choose(QWidget):
    def __init__(self):
        super(face_choose, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("人数设置")
        self.setGeometry(600, 200, 400, 300)
        myframel = QFrame(self)
        myframel.move(105, 50)
        fenge = QLabel(myframel)
        fenge.move(80, 3)
        fenge.setText("至")
        self.xiao = QComboBox(myframel)
        self.xiao.setGeometry(0, 0, 70, 20)
        self.da = QComboBox(myframel)
        self.da.setGeometry(100, 0, 70, 20)
        for item in range(151):
            str1 = "%d" % item
            self.xiao.addItem(str1)
        for item in range(151):
            str2 = "%d" % item
            self.da.addItem(str2)

        butt = QPushButton(self)
        butt.setGeometry(170, 220, 50, 25)
        butt.setText("确认")
        butt.clicked.connect(self.to_get_face)

    def to_get_face(self):
        self.get_tmin = self.xiao.currentText()
        self.get_tmax = self.da.currentText()
        face_ok()


app = QtWidgets.QApplication(sys.argv)
# tmain = the_mainUi()
a = AUi()
TSearch = searchUi()
# PWatch=IconListWidget()
FS = faceUi()
t_time = timeUi()
set_t = time_choose()
set_f = face_choose()

if __name__ == '__main__':
    # tmai
    # tmain.func_upload.clicked.connect(to_A)
    # tmain.func_search.clicked.connect(to_search)
    # tmain.pushButton_2.clicked.connect(to_PW)
    # tmain.pushButton_3.clicked.connect(to_FS)

    t_time.func_deliver.clicked.connect(to_A)
    # 人物搜索
    a.back_to_main.clicked.connect(Backa)

    # 搜索框
    TSearch.show()
    TSearch.func_search.click()
    TSearch.func_deliver.clicked.connect(to_A)

    # PW
    # PWatch.back_to_main.clicked.connect(to_PW_BACK)

    # FS
    FS.func_deliver.clicked.connect(to_A)

    sys.exit(app.exec_())
